<template>
	<view class="appeal-page">
		<view class="reason" v-if="appealStatus ==4">
			<view class="uni-title">申诉原因：</view>
			<view class="uni-textarea">
				<textarea maxlength="2000" v-model="appealForm.appeal_why" auto-height />
			</view>
		</view>
		<view class="upload-box" v-if="appealStatus == 4">
			<view class="uni-title">上传截图凭证:</view>
			<view class="upload-img" ref="one" @click="chooseImage('one')">
				<view class="img-upload">
					<view class="img-add" v-if="imgUrl.one == ''">
						<view class="upload-icon el-icon-ali-upload-img"></view>
					</view>
				</view>
			</view>
			<view class="upload-img" ref="two" @click="chooseImage('two')" v-if="imgUrl.one">
				<view class="img-upload">
					<view class="img-add" v-if="imgUrl.two == ''">
						<view class="upload-icon el-icon-ali-upload-img"></view>
				    </view>
				</view>
			</view>
			<view class="upload-img" ref="three" @click="chooseImage('three')" v-if="imgUrl.two">
				<view class="img-upload">
					<view class="img-add" v-if="imgUrl.three == ''">
						<view class="upload-icon el-icon-ali-upload-img"></view>
					</view>
				</view>
			</view>
		</view>

		<view class="show-img-box" v-else>
			<view v-if="imgArr.length != 0">
				<view class="uni-title" style="color: #4b95ff;">上传截图凭证:</view>
				<image class="img" v-for="(item,index) in imgArr" :key="index" :src="item" mode=""></image>
			</view>
		</view>
		<view v-if="appealStatus != 4">
			<view style="margin-bottom: 10px; font-size: 32upx;" v-for="(item,index) in appealData" :key="index">
				<view style="color: #4b95ff;">
					第{{getSerialNumber(index+1)}}次申诉原因：{{item.why}}
				</view>
				<view class="show-img-box" v-if="(appealStatus != 4) && (appealResultImgUrls.length != 0)">
					<view>
						<view class="uni-title" style="color: #ee7b5a;">申诉结果截图:</view>
						<image class="img" v-for="(item,index) in appealResultImgUrls" :key="index" :src="item" mode=""></image>
					</view>
				</view>
				<view style="color: #ee7b5a;">
					第{{getSerialNumber(index+1)}}次申诉结果：{{item.result}}
				</view>
			</view>

		</view>
		<view class="reappeal-btn themeBackgroundColor" @click="reappeal" v-if="/*appealStatus==3*/false">
			重新申诉
		</view>
		<view class="reason" v-if="isShowReappealWhy">
			<view class="uni-title">重新申诉原因：</view>
			<view class="uni-textarea">
				<textarea maxlength="2000" v-model="reappeal_why" auto-height />
			</view>
		</view>
		<button v-if="appealStatus==4" :loading="loading" :disabled="loading" class="submit-btn" @click="completeAppeal">提交申诉</button>
		<button v-if="isShowReappealWhy" :loading="loading" :disabled="loading" class="submit-btn" @click="reompleteAppeal">提交申诉</button>
	</view>
</template>

<script>
	import qiniuUploader from '../../components/qiniu/qiniuUploader.js';
	import {
		apiGetAppealInfo,
		apiCreatePushAppeal,
		apiAgainAppeal,
		apiUploadToken
	} from '../../../http/apis.js'
	import {
		mapState
	} from 'vuex'
	export default {
		computed: {
			...mapState(['token'])
		},
		data() {
			return {
				appealForm:{
					token: '',
					task_type: '',
					task_code: '',
					type: 2,
					appeal_why: '',
					proof_img_url:'',
					order_num: '',
					tb_name: '',
				},
				imgUrl: {
					one: '',
					two: '',
					three: ''
				},
				uploadToken: '',
				appealStatus: 4,// 是否展示提交
				imgArr: [],
				appealResultImgUrls: [],
				appealData: [],
				isShowReappealWhy: false,// 是否展示重新申述的按钮
				reappeal_why: '',// 重新申述的描述
				appealTaskId: '',
				tabType: 1,
				loading: false
			};
		},
		onLoad(options) {
			this.appealStatus = options.status
			this.appealForm.task_type = options.type
			this.appealForm.task_code = options.taskCode
			this.appealForm.order_num = options.orderNum
			this.appealForm.tb_name = options.tbName
			this.tabType = options.tabType
			this.appealForm.token = this.token
			if (options.merchant_id) this.appealForm.merchant_id = options.merchant_id
			apiUploadToken({}).then(res =>{
			    if(res.data.code == 1)  {
					this.uploadToken = res.data.msg
				}
			}).catch(res => {
				this.$msg.showToast(res.data.msg)
			})
			if(this.appealStatus !=4){
				apiGetAppealInfo({
					token: this.appealForm.token,
					task_type: this.appealForm.task_type,
					type: 2,
					task_code: this.appealForm.task_code
				}).then(res =>{
				    if(res.data.code == 1)  {
						if(res.data.msg.proof_img_url){
							this.imgArr =  res.data.msg.proof_img_url.split(',')
							if (res.data.msg.appeal_result_img_url) {
								this.appealResultImgUrls =  res.data.msg.appeal_result_img_url.split(',')
							}
							this.appealTaskId = res.data.msg.id
							this.appealData =  res.data.msg.appeal_why_result
						}
					}
				}).catch(res => {
					this.$msg.showToast(res.data.msg)
				})
			}
		},
		onShow() {

		},
		onHide() {},
		methods: {
			getSerialNumber(num){
				 let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']; //changeNum[0] = "零"
				    let unit = ["", "十", "百", "千", "万"];
				    num = parseInt(num);
				    let getWan = (temp) => {
				    let strArr = temp.toString().split("").reverse();
				    let newNum = "";
				    for (var i = 0; i < strArr.length; i++) {
				      newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
				    }
				     return newNum;
				   }
				   let overWan = Math.floor(num / 10000);
				   let noWan = num % 10000;
				   if (noWan.toString().length < 4) noWan = "0" + noWan;
				   return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
			},
			// 重新申述
			reappeal(){
				this.isShowReappealWhy = true
			},
			chooseImage(type) {
				var that = this
				uni.chooseImage({
					count: 1,
					sizeType: ['origial'],
					success: res => {
						var uploads = ''
						if(type == 'one'){
							uploads = that.$refs.one.$el;
						} else if(type == 'two') {
							uploads = that.$refs.two.$el;
						} else {
							uploads = that.$refs.three.$el;
						}
						const uploadBox = uploads.querySelector('.img-upload');
						uploadBox.style.backgroundImage = `url('${res.tempFilePaths[0]}')`;
						uploadBox.className = 'img-upload';
						// that.files[type].filePath = res.tempFilePaths[0];
						that.uploadImg(res,res.tempFiles[0].size > 1570000,type);
					},
					fail: function() {
						that.$msg.showToast('载入图片失败，请稍后再试')
					}
				});
			},
			uploadImg(typeimg,fileSize,type){
				var that = this;
				uni.showLoading({
					title: '上传中',
					mask: true
				})
				uni.getImageInfo({
					src:typeimg.tempFilePaths[0],
					success(res) {
						let canvasWidth = res.width //图片原始长宽
						let canvasHeight = res.height
						let img = new Image()
						img.src = res.path
						let canvas = document.createElement('canvas');
						let ctx = canvas.getContext('2d')
						let scale = res.height/res.width
						canvas.width = fileSize == true ? 500 : canvasWidth
						canvas.height = fileSize == true ? 500*scale : canvasHeight
						ctx.drawImage(img, 0, 0, fileSize == true ? 500 : canvasWidth , fileSize == true ? 500*scale : canvasHeight )//fileSize == true ? 300 : canvasHeight / 2

						canvas.toBlob(function(fileSrc) {
							let imgSrc = window.URL.createObjectURL(fileSrc)
							var random = Math.floor(Math.random() * (1000 - 1)) + 1
							var timestamp=new Date().getTime();
							var name=imgSrc.substring(imgSrc.lastIndexOf("-")+1);
							var key = name + random.toString() + timestamp.toString() + '.png'
							 qiniuUploader.upload(
							    imgSrc,
							    res => {
							        //图片上传完成后返回值
									that.imgUrl[type] = res.imageURL;
									that.$msg.showToast('上传成功')
							    },
							    error => {
							        // resolve(error)
									uni.hideLoading()
									that.$msg.showToast('上传失败')
							    },
							    {
							        region: that.GLOBAL.REGION_VALUE, // （必须填写正确）ECN, SCN, NCN, NA, ASG，分别对应七牛的：华东，华南，华北，北美，新加坡 5 个区域
							        domain: that.GLOBAL.QINIU_URL, // // bucket 域名，下载资源时用到。如果设置，会在 success callback 的 res 参数加上可以直接使用的 ImageURL                                         字  段。否则需要自己拼接
							        key: 'screenshot/' + key, // [非必须]自定义文件 key。如果不设置，默认为使用微信小程序 API 的临时文件名
							        // 以下方法三选一即可，优先级为：uptoken > uptokenURL > uptokenFunc
							        uptoken: that.uploadToken // 由其他程序生成七牛 uptoken
							    },
							    res => {
							         //上传进度
							        if(res.progress === 100){
										uni.hideLoading()
							        }
							    }
							);
						})
					}
				})

			},
			completeAppeal(){
				if(!this.appealForm.appeal_why){
					this.$msg.showToast('请填写申诉原因')
					return
				}
				var imgUrlString = ''
				Object.values(this.imgUrl).forEach((item, index) => {
				    if(item){
						imgUrlString += item + ','
					}
				})
				if(!imgUrlString){
					uni.showToast({title:'请先上传图片',duration: 1000,icon:'none'})
					return
				}
				this.appealForm.proof_img_url = imgUrlString.substring(0,imgUrlString.length-1)
				uni.showLoading({
					title: '提交中...',
					mask: true
				})
				this.loading = true
				apiCreatePushAppeal(this.appealForm).then(res =>{
					uni.hideLoading()
				    if(res.data.code == 1)  {
						this.$msg.showToast(res.data.msg)
						setTimeout(()=>{
							this.loading = false
							uni.switchTab({
								url: './taskList'
							});
						},1000)
					} else {
						this.loading = false
						this.$msg.showToast(res.data.msg)
					}
				}).catch(res => {
					uni.hideLoading()
					this.loading = false
					this.$msg.showToast(res.data.msg)
				})
			},
			reompleteAppeal(){
				if(!this.reappeal_why){
					this.$msg.showToast('请填写重新申诉原因')
					return
				}
				var result = ''
				var why = ''
				for (var i in this.appealData) {
					result += this.appealData[i].result + '|'
					why += this.appealData[i].why + '|'
				}
				why += this.reappeal_why
				result = result.substring(0,result.length-1)

				uni.showLoading({
					title: '提交中...',
					mask: true
				})
				this.loading = true
				apiAgainAppeal({
					token: this.token,
					appealTaskId: this.appealTaskId,
					result: result,
					why: why,
				}).then(res =>{
					uni.hideLoading()
				    if(res.data.code == 1)  {
						this.$msg.showToast(res.data.msg)
						setTimeout(()=>{
							this.loading = false
							uni.switchTab({
								url: './taskList'
							});
						},1000)
					} else {
						this.loading = false
						this.$msg.showToast(res.data.msg)
					}
				}).catch(res => {
					uni.hideLoading()
					this.loading = false
					this.$msg.showToast(res.data.msg)
				})
			}
		},
		mounted() {
			// this.planList();
		}
	};
</script>

<style lang="scss">
	page {
		background: #FFFFFF;
		padding: 0 20upx;
	}
	.appeal-page {
		overflow-y: scroll;
		overflow-x: hidden;
		margin-bottom: 150upx;
		.reason {
			margin-top: 20upx;
		}
		.uni-title {
			font-size: 28upx;
			margin-bottom: 10upx;
		}
		.uni-textarea {
			border: 1px solid #E0E0E0;
			border-radius: 5upx;
			padding: 20upx;
			uni-textarea {
				font-size: 28upx!important;
			}

		}
		.upload-box {
			margin-top: 40upx;
			.upload-img {
				display: inline-block;
				margin-right: 20upx;
				margin-bottom: 20upx;
				vertical-align: middle;
			}
			.img-upload {
				// width: 100px;
				// height: 100px;
				border: 0.5px dotted gray;
				position: relative;
				width: 210upx;
				height: 320upx;
				box-sizing: border-box;
				background-size: cover;
				background-repeat: no-repeat;
				background-position: center;
				border-radius: 10upx;
				.img-add {
					font-size: 60upx;
					line-height: 320upx;
					text-align: center;
					.upload-icon {
						font-size: 50upx;
						color: #666666;
					}
				}
			}
		}
		.submit-task {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			font-size: 18px;
			color: #fff;
			text-align: center;
			line-height: 50px;
		}
		.appeal-result {
			margin-top: 20upx;
		}
		.show-img-box {
			margin-top: 30upx;
			.img {
				width: 210upx;
				height: 320upx;
				border: 1px solid #e0e0e0;
				margin-right: 20upx;
				margin-bottom: 20upx;
			}
		}
		.reappeal-btn {
			margin: 30upx auto;
			// display: inline-block;
			width: 200upx;
			text-align: center;
			color: #FFFFFF;
			padding: 14upx;
			border-radius: 10upx;
		}
		.submit-btn {
			position: fixed;
			bottom: 32upx;
			left: 32upx;
			right: 32upx;
			font-size: 18px;
			color: #fff;
			text-align: center;
			line-height: 50px;
			background: $theme-background-color;
		}
	}
</style>
